package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.aries.ui.view.radius.RadiusRadioButton;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.CommVLayoutAdapter;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.BaiDuLocationInfo;
import com.chexiehui.jc.entity.ShopInfo;
import com.chexiehui.jc.mvp.home.Shop4sChooseCovenant;
import com.chexiehui.jc.mvp.home.Shop4sChoosePresenter;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.widget.LoadingLayout;
import com.nex3z.flowlayout.FlowLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 4s店选择
 */
public class Shop4sChooseActivity extends BaseMvpActivity<Shop4sChoosePresenter> implements Shop4sChooseCovenant.View {
    @BindView(R.id.recycler)
    RecyclerView mRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rrb_desc_type_0)
    RadiusRadioButton rrbDescType0;
    @BindView(R.id.rrb_desc_type_1)
    RadiusRadioButton rrbDescType1;
    @BindView(R.id.fl_follow_tip)
    FlowLayout flFollowTip;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;

    private DelegateAdapter listAdapter;
    private CommVLayoutAdapter<ShopInfo> shopAdapter;
    private BasePage<ShopInfo> page;

    private BaiDuLocationInfo baiDuLocationInfo;
    private int descType;
    private ArrayList<String> choose = new ArrayList<>();
    private String carId;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            baiDuLocationInfo = (BaiDuLocationInfo) bundle.getSerializable("location");
            carId = bundle.getString("carId");
        }
        if (baiDuLocationInfo == null) {
            baiDuLocationInfo = new BaiDuLocationInfo();
        }
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("选择经销商")
                .setRightText("")
                .setOnRightTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        if(choose == null || choose.size() < 1){
                            showToast("请选择");
                            return;
                        }
                        Intent intent = new Intent();
                        intent.putStringArrayListExtra("chooseList", choose);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_shop_4s_choose;
    }

    @Override
    protected void initView(Bundle var1) {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        loadingLayout.setStatus(LoadingLayout.Loading);
        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getShopList(1);
        });
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(mContext);
        mRecycler.setLayoutManager(virtualLayoutManager);
        ((SimpleItemAnimator) mRecycler.getItemAnimator()).setSupportsChangeAnimations(false);
        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecycler.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 20);
        listAdapter = new DelegateAdapter(virtualLayoutManager, false);
        mRecycler.setAdapter(listAdapter);

        int dp_10 = SizeUtils.dp2px(10);
        LinearLayoutHelper helper = new LinearLayoutHelper(dp_10);
        helper.setPadding(dp_10, dp_10, dp_10, dp_10);
        helper.setBgColor(ContextCompat.getColor(mContext, R.color.colorTransparent));
        shopAdapter = new CommVLayoutAdapter<ShopInfo>(mContext, new ArrayList<>(),
                R.layout.item_4s_shop_choose, helper) {
            @Override
            public void convert(ViewHolder holder, int position, ShopInfo item) {
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_address, item.getAdress());
                holder.setText(R.id.tv_item_brand, "主营品牌：" + item.getBrandName());
                holder.setText(R.id.tv_item_distance, "距离" + item.getDistanceStr());
                TextView tv_item_other_brand = holder.getView(R.id.tv_item_other_brand);
                if(StringUtils.isTrimEmpty(item.getOtherBrand())){
                    tv_item_other_brand.setVisibility(View.GONE);
                }else{
                    tv_item_other_brand.setVisibility(View.VISIBLE);
                    tv_item_other_brand.setText("其他品牌：" + item.getOtherBrand());
                }
                holder.setImageResource(R.id.iv_item_check, choose.contains(item.getId()) ? R.mipmap.ic_check_s : R.mipmap.ic_check_us);
                holder.getView(R.id.rtv_item_consult).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        if (StringUtils.isTrimEmpty(item.getTel())) {
                            showToast("暂无联系方式");
                        } else {
                            callPhone(item.getTel());
                        }
                    }
                });
            }
        };
        shopAdapter.setItemClickListener((view, position, item) -> {
            if(choose.contains(item.getId())){
                choose.remove(item.getId());
            }else{
                choose.add(item.getId());
            }
            shopAdapter.notifyDataSetChanged();
            changeRight();
        });
        listAdapter.addAdapter(shopAdapter);

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            if(loadingLayout.getStatus() == LoadingLayout.Loading){
                refreshLayout.finishRefresh();
                return;
            }
            mvpPresenter.getShopList(1);
        });
        changeDescType(0);
        changeRight();
        mvpPresenter.getShopList(1);
    }

    private void changeRight(){
        if(choose != null && choose.size() > 0){
            titleBar.setRightText("确定");
        }else{
            titleBar.setRightText("");
        }
    }

    private void callPhone(String phone) {
        AndPermission.with(this)
                .permission(Permission.PHONE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PhoneUtils.call(phone);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权电话权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    private void changeDescType(int index) {
        if (index == descType) {
            return;
        }
        descType = index;
        if (descType == 0) {
            rrbDescType0.setSelected(true);
            rrbDescType1.setSelected(false);
        } else {
            rrbDescType0.setSelected(false);
            rrbDescType1.setSelected(true);
        }
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<ShopInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            shopAdapter.getData().clear();
            shopAdapter.getData().addAll(page.getItems());
            shopAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            shopAdapter.getData().addAll(page.getItems());
            shopAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= shopAdapter.getData().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            shopAdapter.getData().clear();
            shopAdapter.getData().addAll(page.getItems());
            shopAdapter.notifyDataSetChanged();
        }
        if(loadingLayout.getStatus() == LoadingLayout.Loading){
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (shopAdapter.getData().size() > 0) {
                    shopAdapter.getData().clear();
                    shopAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (shopAdapter.getData().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public String getLocationLat() {
        return baiDuLocationInfo != null ? baiDuLocationInfo.getLat() + "" : "";
    }

    @Override
    public String getLocationLng() {
        return baiDuLocationInfo != null ? baiDuLocationInfo.getLng() + "" : "";
    }

    @Override
    public String getLocationCity() {
        return baiDuLocationInfo.getCity() == null ? "" : baiDuLocationInfo.getCity();
    }

    @Override
    public String getCarId() {
        return carId == null ? "" : carId;
    }

    @Override
    public String getDescType() {
        return descType + "";
    }

    @OnClick({R.id.rrb_desc_type_0, R.id.rrb_desc_type_1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rrb_desc_type_0:
                if (descType != 0) {
                    changeDescType(0);
                    loadingLayout.setStatus(LoadingLayout.Loading);
                    mvpPresenter.getShopList(1);
                }
                break;
            case R.id.rrb_desc_type_1:
                if (descType != 1) {
                    changeDescType(1);
                    loadingLayout.setStatus(LoadingLayout.Loading);
                    mvpPresenter.getShopList(1);
                }
                break;
        }
    }

    @Override
    protected Shop4sChoosePresenter createPresenter() {
        return new Shop4sChoosePresenter(this);
    }
}
